package com.fotile.plugin;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.provider.Settings;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;

/**
 * 插件：WiFi + 定位交互
 * 支持精确定位权限申请 + 定位获取
 */
public class WifiStatusChannel implements FlutterPlugin, MethodChannel.MethodCallHandler, ActivityAware {

    private MethodChannel channel;
    private Activity activity;

    private static final int REQUEST_LOCATION_PERMISSION = 1001;
    private MethodChannel.Result pendingResult; // 保存 Flutter 回调，等待权限结果

    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) {
        channel = new MethodChannel(binding.getBinaryMessenger(), "WifiStatusChannel");
        channel.setMethodCallHandler(this);
    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
        channel.setMethodCallHandler(null);
    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
        switch (call.method) {
            case "getCurrentLocation":
                handleGetCurrentLocation(result);
                break;
            case "isWifiEnabled":
                result.success(isWifiEnabled());
                break;
            case "openWifiSettings":
                openWifiSettings();
                result.success(null);
                break;
            case "getWifiList":
                getWifiScanResults(result);
                break;
            default:
                result.notImplemented();
        }
    }

    /**
     * 处理定位请求：先检查权限，没有就申请
     */
    private void handleGetCurrentLocation(MethodChannel.Result result) {
        if (activity == null) {
            result.error("NO_ACTIVITY", "Activity is null", null);
            return;
        }

        // 检查权限
        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            // 保存 result 等待回调
            pendingResult = result;

            ActivityCompat.requestPermissions(activity,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    REQUEST_LOCATION_PERMISSION);
            return;
        }

        // 已有权限 → 获取定位
        fetchLocation(result);
    }

    // 判断 WiFi 是否开启
    private boolean isWifiEnabled() {
        if (activity == null) return false;
        WifiManager wifiManager = (WifiManager) activity.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        return wifiManager != null && wifiManager.isWifiEnabled();
    }

    // 打开 WiFi 设置界面
    private void openWifiSettings() {
        if (activity == null) return;
        android.content.Intent intent = new android.content.Intent(android.provider.Settings.ACTION_WIFI_SETTINGS);
        activity.startActivity(intent);
    }

    // 扫描周围热点
    private void getWifiScanResults(MethodChannel.Result result) {
        WifiManager wifiManager = (WifiManager) activity.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (wifiManager == null) {
            result.error("NO_WIFI", "WifiManager is null", null);
            return;
        }

        // 先请求一次扫描（Android 9 之后需要定位权限才返回）
        boolean success = wifiManager.startScan();
        if (!success) {
            result.error("SCAN_FAILED", "startScan failed", null);
            return;
        }

        if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        List<ScanResult> scanResults = wifiManager.getScanResults();
        List<Map<String, Object>> wifiList = new ArrayList<>();

        for (ScanResult scanResult : scanResults) {
            Map<String, Object> wifiInfo = new HashMap<>();
            wifiInfo.put("SSID", scanResult.SSID);
            wifiInfo.put("BSSID", scanResult.BSSID);
            wifiInfo.put("level", scanResult.level); // 信号强度
            wifiInfo.put("frequency", scanResult.frequency); // 频率
            wifiList.add(wifiInfo);
        }

        result.success(wifiList);
    }


    /**
     * 真正执行定位（带权限检查 + 异常处理）
     */
    private void fetchLocation(MethodChannel.Result result) {
        try {
            if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
                result.error("NO_PERMISSION", "缺少定位权限", null);
                return;
            }

            LocationManager locationManager = (LocationManager) activity.getSystemService(Activity.LOCATION_SERVICE);
            Location location = null;

            if (locationManager != null) {
                // GPS 优先
                location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                // 网络兜底
                if (location == null) {
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                }
            }

            if (location != null) {
                double latitude = location.getLatitude();
                double longitude = location.getLongitude();
                result.success("lat:" + latitude + ", lng:" + longitude);
            } else {
                result.error("NO_LOCATION", "无法获取位置信息，请确认已打开GPS", null);
            }
        } catch (SecurityException se) {
            result.error("SECURITY_EXCEPTION", "缺少定位权限: " + se.getMessage(), null);
        } catch (Exception e) {
            result.error("LOCATION_ERROR", e.getMessage(), null);
        }
    }

    // =============== 权限回调处理 =================
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode == REQUEST_LOCATION_PERMISSION && pendingResult != null) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 用户允许 → 获取位置
                fetchLocation(pendingResult);
            } else {
                // 用户拒绝
                if (!ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.ACCESS_FINE_LOCATION)) {
                    // 永久拒绝
                    pendingResult.error("PERMISSION_DENIED_FOREVER", "用户永久拒绝了定位权限", null);
                } else {
                    // 一次性拒绝
                    pendingResult.error("PERMISSION_DENIED", "用户拒绝了定位权限", null);
                }
            }
            pendingResult = null;
        }
    }

    // =============== Activity 生命周期 =================
    @Override
    public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
        this.activity = binding.getActivity();

        // 注册权限回调
        binding.addRequestPermissionsResultListener((requestCode, permissions, grantResults) -> {
            onRequestPermissionsResult(requestCode, permissions, grantResults);
            return true;
        });
    }

    @Override
    public void onDetachedFromActivityForConfigChanges() {
        this.activity = null;
    }

    @Override
    public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) {
        this.activity = binding.getActivity();
    }

    @Override
    public void onDetachedFromActivity() {
        this.activity = null;
    }
}
